package com.hengpeng.common.config.expander;

import java.util.HashMap;
import java.util.Map;

/**
 * <pre>
 * 扩展读取配置特殊符号${}功能
 * </pre>
 * @author chenjian
 * @version 1.0, 2010-12-23
 */
public class VariablesExpander
{
	private PropertiesExpander config;

	private String pre;

	private String suf;

	public static final int MAX_EXPANDER = 15;

	private Map<String, String> __cacheMap = new HashMap<String, String>();

	/**
	 * 构造函数
	 * @param config 属性文件读取接口
	 * @param pre 扩展前缀
	 * @param suf 扩展后缀
	 */
	public VariablesExpander(PropertiesExpander config, String pre, String suf)
	{
		this.config = config;
		this.pre = pre;
		this.suf = suf;
	}

	/**
	 * <pre>
	 * 读取属性值，并且解析其${}信息
	 * </pre>
	 * @param value 属性值
	 * @return 真实属性值
	 */
	public String getVariablesExpanderValue(String value)
	{
		String result = value;
		if (__cacheMap.get(value) != null)
		{
			return __cacheMap.get(value);
		}
		boolean isHaveExpander = false;
		boolean found = true;
		int count = 0;
		while (found && count < MAX_EXPANDER)
		{
			int start = result.indexOf(pre);
			if (start != -1)
			{
				int end = result.indexOf(suf);
				if (end != -1)
				{
					found = true;
					isHaveExpander = true;
					String pree = result.substring(0, start);
					String suff = result.substring(end + suf.length());
					String name = result.substring(start + pre.length(), end);
					result = pree + config.getConfigByKey(name) + suff;
					count++;
					continue;
				}
			}
			found = false;
		}
		if (isHaveExpander)
		{
			__cacheMap.put(value, result);
		}
		return result;
	}

	public void clearCache()
	{
		__cacheMap.clear();
	}
}
